<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :sm="24" :lg="24" style="padding-left: 20px">
        <h2>小管家 - 数据统计</h2>
      </el-col>
    </el-row>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="日期范围" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-select v-model="queryParams.className" placeholder="请选择班级" clearable style="width: 200px">
            <el-option
              v-for="item in classOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="statistics-overview" v-loading="loading">
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon total">
              <i class="el-icon-user"></i>
            </div>
            <div class="overview-content">
              <div class="overview-number">{{ statisticsData.totalStudents }}</div>
              <div class="overview-label">总学生数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon submitted">
              <i class="el-icon-check"></i>
            </div>
            <div class="overview-content">
              <div class="overview-number">{{ statisticsData.submitRate }}%</div>
              <div class="overview-label">总体提交率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon ontime">
              <i class="el-icon-time"></i>
            </div>
            <div class="overview-content">
              <div class="overview-number">{{ statisticsData.onTimeRate }}%</div>
              <div class="overview-label">按时提交率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-item">
            <div class="overview-icon late">
              <i class="el-icon-warning"></i>
            </div>
            <div class="overview-content">
              <div class="overview-number">{{ statisticsData.lateRate }}%</div>
              <div class="overview-label">迟交率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 统计表格 -->
    <el-card class="table-card" shadow="never">
      <div slot="header" class="clearfix">
        <span>学生作业提交情况统计</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text" 
          @click="exportData"
          :loading="exportLoading"
          :disabled="tableData.length === 0"
        >
          <i class="el-icon-download"></i> 导出数据
        </el-button>
      </div>
      
      <!-- 空数据提示 -->
      <div v-if="!loading && tableData.length === 0" class="empty-data">
        <el-empty description="暂无数据">
          <el-button type="primary" @click="handleQuery">重新加载</el-button>
        </el-empty>
      </div>
      
      <el-table 
        v-else
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        element-loading-text="正在加载数据..."
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column prop="序号" label="序号" width="60" align="center" />
        <el-table-column prop="姓名" label="姓名" width="100" align="center" />
        <el-table-column prop="Name" label="Name" width="120" align="center" />
        
        <!-- 动态生成日期列和积分列 -->
        <template v-for="date in dateColumns">
          <!-- 日期提交状态列 -->
          <el-table-column
            :key="'status-' + date"
            :label="formatDateLabel(date)"
            width="80"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.dailyData && scope.row.dailyData[date]" class="daily-submit-cell">
                <!-- 提交状态图标 -->
                <div class="submit-status">
                  <i 
                    :class="scope.row.dailyData[date].submitted ? 'el-icon-check submit-icon-success' : 'el-icon-close submit-icon-fail'"
                    :title="scope.row.dailyData[date].submitted ? '已提交' : '未提交'"
                  ></i>
                  <span v-if="scope.row.dailyData[date].isLate" class="late-indicator" title="迟交">迟</span>
                </div>
              </div>
              <span v-else class="no-data">-</span>
            </template>
          </el-table-column>
          
          <!-- 对应日期的积分列 -->
          <el-table-column
            :key="'reward-' + date"
            :label="'积分'"
            width="60"
            align="center"
          >
            <template slot-scope="scope">
              <div 
                class="daily-reward"
                :class="{
                  'reward-zero': !scope.row.rewardData || !scope.row.rewardData[date] || scope.row.rewardData[date] === 0,
                  'reward-positive': scope.row.rewardData && scope.row.rewardData[date] && scope.row.rewardData[date] > 0
                }"
              >
                {{ (scope.row.rewardData && scope.row.rewardData[date]) || 0 }}
              </div>
            </template>
          </el-table-column>
        </template>
        
        <!-- 总积分列 -->
        <el-table-column label="总积分" width="80" align="center">
          <template slot-scope="scope">
            <div 
              class="reward-total"
              :class="{
                'total-zero': !scope.row.totalRewardScore || scope.row.totalRewardScore === 0,
                'total-positive': scope.row.totalRewardScore && scope.row.totalRewardScore > 0
              }"
            >
              {{ scope.row.totalRewardScore || 0 }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="提交统计" width="120" align="center">
          <template slot-scope="scope">
            <div class="submit-stats">
              <div>已交: {{ scope.row.submittedCount || 0 }}</div>
              <div>未交: {{ scope.row.unsubmittedCount || 0 }}</div>
              <div>迟交: {{ scope.row.lateCount || 0 }}</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { getSubmitStatistics, getStatisticsOverview, getClassOptions, exportStatistics, getDailySubmitDetail } from "@/api/manage/statistics"

export default {
  name: "Index",
  data() {
    return {
      // 查询参数
      queryParams: {
        className: null
      },
      dateRange: [],
      showSearch: true,
      loading: false,
      exportLoading: false,
      
      // 班级选项
      classOptions: [],
      
      // 统计数据
      statisticsData: {
        totalStudents: 0,
        submitRate: 0,
        onTimeRate: 0,
        lateRate: 0
      },
      
      // 日期列
      dateColumns: [],
      
      // 表格数据
      tableData: []
    }
  },
  created() {
    this.getClassList()
    this.getStatisticsData()
  },
  methods: {
    /** 获取班级列表 */
    getClassList() {
      getClassOptions().then(response => {
        // 处理后端返回的数据结构
        const data = response.data || []
        this.classOptions = data.map(item => ({
          value: item.value,
          label: item.label
        }))
      }).catch(error => {
        console.error('获取班级列表失败:', error)
        this.$message.error('获取班级列表失败')
      })
    },
    
    /** 获取统计数据 */
    getStatisticsData() {
      this.loading = true
      
      // 构建查询参数
      const params = {
        classCode: this.queryParams.className
      }
      
      // 添加日期范围参数
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0]
        params.endDate = this.dateRange[1]
      }
      
      // 获取概览数据
      this.getStatisticsOverview(params)
      
      // 获取每日详情数据
      this.getDailySubmitDetail(params)
    },
    
    /** 获取统计概览数据 */
    getStatisticsOverview(params) {
      getStatisticsOverview(params).then(response => {
        const data = response.data || {}
        this.statisticsData = {
          totalStudents: data.totalStudents || 0,
          submitRate: data.submitRate || 0,
          onTimeRate: data.onTimeRate || 0,
          lateRate: data.lateRate || 0
        }
      }).catch(error => {
        console.error('获取统计概览失败:', error)
        this.$message.error('获取统计概览失败')
      })
    },
    
    /** 获取学生每日提交详情 */
    getDailySubmitDetail(params) {
      getDailySubmitDetail(params).then(response => {
        const data = response.data || {}
        
        // 设置日期列
        this.dateColumns = data.dateColumns || []
        
        // 处理学生数据，添加序号
        const studentData = data.studentData || []
        this.tableData = studentData.map((student, index) => ({
          序号: index + 1,
          姓名: student.studentName,
          Name: student.studentNo,
          dailyData: student.dailyData,
          rewardData: student.rewardData, // 奖励积分数据
          totalRewardScore: student.totalRewardScore || 0, // 总奖励积分
          submittedCount: student.totalSubmits || 0,
          lateCount: student.lateSubmits || 0,
          unsubmittedCount: Math.max(0, this.dateColumns.length - (student.totalSubmits || 0))
        }))
        
        this.loading = false
      }).catch(error => {
        console.error('获取学生每日提交详情失败:', error)
        this.$message.error('获取学生每日提交详情失败')
        this.loading = false
      })
    },
    
    /** 格式化日期标签 */
    formatDateLabel(date) {
      // 将 yyyy-MM-dd 格式转换为 MM.dd 格式
      if (date && date.length >= 10) {
        const month = date.substring(5, 7)
        const day = date.substring(8, 10)
        return `${month}.${day}`
      }
      return date
    },
    
    /** 搜索 */
    handleQuery() {
      this.getStatisticsData()
    },
    
    /** 重置 */
    resetQuery() {
      this.dateRange = []
      this.queryParams = {
        className: null
      }
      this.getStatisticsData()
    },
    
    /** 获取提交状态标签类型 */
    getSubmitStatusTagType(status) {
      switch (status) {
        case '未交':
          return 'danger'
        case '已提交':
          return 'success'
        case '迟交':
          return 'warning'
        default:
          return 'info'
      }
    },
    
    /** 获取提交状态文本 */
    getSubmitStatusText(status) {
      return status || '-'
    },
    
    /** 导出数据 */
    exportData() {
      if (this.tableData.length === 0) {
        this.$message.warning('暂无数据可导出')
        return
      }
      
      this.exportLoading = true
      
      // 构建查询参数
      const params = {
        ...this.queryParams
      }
      
      // 如果有日期范围，添加到参数中
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0]
        params.endDate = this.dateRange[1]
      }
      
      exportStatistics(params).then(response => {
        // 创建下载链接
        const blob = new Blob([response], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `学生作业提交统计_${new Date().getTime()}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        this.$message.success('导出成功')
      }).catch(error => {
        console.error('导出失败:', error)
        if (error.response && error.response.status === 404) {
          this.$message.error('导出接口不存在，请联系管理员')
        } else if (error.response && error.response.status === 500) {
          this.$message.error('服务器错误，导出失败')
        } else {
          this.$message.error('导出失败，请稍后重试')
        }
      }).finally(() => {
        this.exportLoading = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;

    li {
      border-bottom: 1px solid #e7eaec;
      display: block;
      padding: 6px 5px;
      position: relative;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }

  // 新增样式
  .filter-card {
    margin-bottom: 20px;
  }

  .statistics-overview {
    margin-bottom: 20px;
    
    .overview-card {
      .overview-item {
        display: flex;
        align-items: center;
        padding: 10px;
        
        .overview-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          
          i {
            font-size: 24px;
            color: white;
          }
          
          &.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          
          &.submitted {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
          
          &.ontime {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }
          
          &.late {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
        }
        
        .overview-content {
          flex: 1;
          
          .overview-number {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 5px;
          }
          
          .overview-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }

  .table-card {
    .submit-stats {
      font-size: 12px;
      line-height: 1.4;
      
      div {
        margin-bottom: 2px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
    
    .empty-data {
      padding: 40px 0;
      text-align: center;
    }
    
    // 每日提交单元格样式
    .daily-submit-cell {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 4px;
      
      .submit-status {
        display: flex;
        align-items: center;
        gap: 4px;
        
        .submit-icon-success {
          color: #67c23a;
          font-size: 16px;
          font-weight: bold;
        }
        
        .submit-icon-fail {
          color: #f56c6c;
          font-size: 16px;
          font-weight: bold;
        }
        
        .late-indicator {
          background-color: #e6a23c;
          color: white;
          font-size: 10px;
          padding: 1px 4px;
          border-radius: 2px;
          font-weight: bold;
        }
      }
    }
    
    .daily-reward {
      color: #409eff;
      font-size: 12px;
      font-weight: bold;
      
      &.reward-zero {
        color: #c0c4cc;
        background-color: #f5f7fa;
        padding: 2px 6px;
        border-radius: 3px;
        border: 1px solid #e4e7ed;
      }
      
      &.reward-positive {
        color: #67c23a;
        background-color: #f0f9ff;
        padding: 2px 6px;
        border-radius: 3px;
        border: 1px solid #b3d8ff;
      }
    }
    
    .reward-total {
      font-size: 14px;
      font-weight: bold;
      padding: 4px 8px;
      border-radius: 4px;
      
      &.total-zero {
        color: #909399;
        background-color: #f4f4f5;
        border: 1px solid #d3d4d6;
      }
      
      &.total-positive {
        color: #e6a23c;
        background-color: #fdf6ec;
        border: 1px solid #f5dab1;
      }
    }
    
    .no-data {
      color: #c0c4cc;
      font-size: 14px;
    }
  }
}
</style>

